<template>
  <view class="hardware-home">
    <!-- 固定导航栏 -->
    <view class="custom-nav-bar" :style="{ height: navBarHeight + 'px' }">
      <!-- 状态栏占位 -->
      <view :style="{ height: statusBarHeight + 'px' }"></view>
      <!-- 导航栏内容 -->
      <view class="nav-content" :style="{ height: navBarContentHeight + 'px' }">
        <text class="nav-title">警务通</text>
      </view>
    </view>

    <!-- 功能卡片容器 -->
    <view class="card-container" :style="{ paddingTop: navBarHeight + 'px' }">
      <view class="function-card" v-for="(item, index) in functionList" :key="index" @click="handleCardClick(item)"
        tabindex="-1" :class="{active: focusNavigator.getCurrentIndex() === index}">
        <image class="card-icon" :src="item.icon" mode="aspectFit"></image>
        <text class="card-text">{{ item.text }}</text>
      </view>
    </view>
  </view>
</template>

<script setup>
  import {
    ref,
    onMounted,
    onUnmounted
  } from 'vue';
  import {
    onShow
  } from '@dcloudio/uni-app';
  import {
    createFocusNavigator
  } from '../../utils/key.js'

  // 导航栏高度相关变量
  const statusBarHeight = ref(0)
  const navBarContentHeight = ref(44)
  const navBarHeight = ref(0)

  // 定义功能列表数据（链表式，按顺序排列）
  const functionList = ref([{
      text: '消息通知',
      icon: '/static/message.png',
      route: '/pages/notification/notification',
      onSelect: (item) => handleCardClick(item)
    },
    {
      text: '语音对讲',
      icon: '/static/intercom.png',
      route: '/pages/intercom/intercom',
      onSelect: (item) => handleCardClick(item)
    },
    {
      text: '警情发送',
      icon: '/static/send.png',
      route: '/pages/sendNewPage/sendNewPage',
      onSelect: (item) => handleCardClick(item)
    },
    {
      text: '系统设置',
      icon: '/static/setting.png',
      route: '/pages/Setting/Setting',
      onSelect: (item) => handleCardClick(item)
    }
  ]);

  // 创建焦点导航器
  const focusNavigator = createFocusNavigator(functionList.value, 0);

  // 卡片点击事件处理函数
  const handleCardClick = (item) => {
    if (item.route) {
      console.log('准备跳转到:', item.route);

      // 跳转前先清理按键事件监听器，避免与目标页面的冲突
      const sys = uni.getSystemInfoSync();
      if (sys.platform === 'android') {
        try {
          plus.key.removeEventListener('keydown', focusNavigator.handleKeyDown);
          plus.key.removeEventListener('keyup', focusNavigator.handleKeyUp);
          console.log('index页面按键事件已清理');
        } catch (e) {
          console.log('清理按键事件时出错:', e);
        }
      }

      // 延迟跳转，确保事件完全清理
      setTimeout(() => {
        uni.navigateTo({
          url: item.route
        });
      }, 50);
    } else {
      uni.showToast({
        title: '功能开发中...',
        icon: 'none',
        duration: 2000
      });
    }
  };

  onMounted(() => {
    // 计算导航栏高度
    const systemInfo = uni.getSystemInfoSync()
    statusBarHeight.value = systemInfo.statusBarHeight || systemInfo.safeAreaInsets?.top || 20
    navBarHeight.value = statusBarHeight.value + navBarContentHeight.value

    // 确保初始焦点设置正确
    console.log('页面挂载完成，当前焦点索引:', focusNavigator.getCurrentIndex());
    console.log('功能列表长度:', functionList.value.length);

    // 监听按键事件
    const sys = uni.getSystemInfoSync();
    if (sys.platform === 'android') {
      plus.key.addEventListener('keydown', focusNavigator.handleKeyDown);
      plus.key.addEventListener('keyup', focusNavigator.handleKeyUp);
    }
  });

  onShow(() => {
    // 页面重新显示时重新注册按键事件
    console.log('index页面重新显示，重新注册按键事件');

    const sys = uni.getSystemInfoSync();
    if (sys.platform === 'android') {
      // 先尝试清理可能存在的旧监听器
      try {
        plus.key.removeEventListener('keydown', focusNavigator.handleKeyDown);
        plus.key.removeEventListener('keyup', focusNavigator.handleKeyUp);
      } catch (e) {}

      // 重新注册
      plus.key.addEventListener('keydown', focusNavigator.handleKeyDown);
      plus.key.addEventListener('keyup', focusNavigator.handleKeyUp);
      console.log('index页面按键事件重新注册成功');
    }
  });

  onUnmounted(() => {
    const sys = uni.getSystemInfoSync();
    if (sys.platform === 'android') {
      plus.key.removeEventListener('keydown', focusNavigator.handleKeyDown);
      plus.key.removeEventListener('keyup', focusNavigator.handleKeyUp);
    }
    // 清理焦点导航器
    focusNavigator.destroy();
  });
</script>

<style scoped>
  .hardware-home {
    width: 100%;
    height: 100vh;
    background-color: #555;
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  /* 固定导航栏样式 */
  .custom-nav-bar {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    background-color: #333;
    z-index: 999;
  }

  .nav-content {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 12rpx 24rpx;
    box-sizing: border-box;
  }

  .nav-title {
    font-size: 48rpx;
    font-weight: bold;
    color: #fff;
    padding-bottom: 2px;
  }

  /* 功能卡片容器样式 */
  .card-container {
    width: 90%;
    display: grid;
    grid-template-columns: 1fr 1fr;
    grid-template-rows: 1fr 1fr;
    gap: 40rpx;
    padding: 60rpx 10rpx;
    box-sizing: border-box;
    margin-top: 40rpx;
  }

  /* 功能卡片样式 */
  .function-card {
    background-color: #333;
    border-radius: 20rpx;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 40rpx 20rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.3);
    transition: all 0.3s ease;
    min-height: 200rpx;
    outline: none;
  }

  .function-card:focus {
    outline: none;
  }

  .function-card:active {
    transform: scale(0.95);
    background-color: #444;
  }

  /* 激活 (焦点) 样式 */
  .function-card.active {
    background-color: #007bff;
    color: white;
    transform: scale(1.05);
    box-shadow: 0 4px 12px rgba(0, 123, 255, 0.3);
  }

  .function-card.active .card-text {
    color: white;
  }

  /* 卡片图标样式 */
  .card-icon {
    width: 160rpx;
    height: 160rpx;
    margin-bottom: 30rpx;
  }

  /* 卡片文字样式 */
  .card-text {
    font-size: 40rpx;
    color: #fff;
    text-align: center;
    font-weight: 500;
  }

  /* 全局禁用焦点样式 */
  :focus {
    outline: none !important;
  }

  /* 禁用系统默认的焦点框 */
  *:focus {
    outline: none !important;
    box-shadow: none !important;
  }

  /* 禁用Android系统默认的橙色焦点框 */
  .function-card:focus-visible {
    outline: none !important;
    box-shadow: none !important;
  }
</style>